package com.example.lotterysystem.dao.handler;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import com.example.lotterysystem.dao.dataobject.Encrypt;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.nio.charset.StandardCharsets;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes(Encrypt.class)   //指定的类型
@MappedJdbcTypes(JdbcType.VARCHAR)  //jdbc类型
public class EncryptTypeHandler extends BaseTypeHandler<Encrypt> {

    private byte[] KEY="1122334455aabbcc".getBytes(StandardCharsets.UTF_8);

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Encrypt parameter, JdbcType jdbcType) throws SQLException {
        if(parameter==null){
            ps.setString(i,null);
            return;
        }

        AES aes= SecureUtil.aes(KEY);
        String str=aes.encryptHex(parameter.getValue());

        System.out.println("加密后的数据： "+str);
        ps.setString(i, str);

    }

    @Override
    public Encrypt getNullableResult(ResultSet rs, String columnName) throws SQLException {
        System.out.println("解密前数据： "+rs.getString(columnName));

       return deEncrypt(rs.getString(columnName));
    }

    @Override
    public Encrypt getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        System.out.println("解密前数据： "+rs.getString(columnIndex));

        return deEncrypt(rs.getString(columnIndex));

    }

    @Override
    public Encrypt getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        System.out.println("解密前数据： "+cs.getString(columnIndex));
        return deEncrypt(cs.getString(columnIndex));

    }

    private Encrypt deEncrypt(String val){

        if(val==null) return null;
        AES aes= SecureUtil.aes(KEY);
        return new Encrypt(aes.decryptStr(val));
    }
}
